//
//  ZLPSubDetailViewController.m
//  TangYi
//
//  Created by dllo on 15/10/29.
//  Copyright © 2015年 赵连鹏. All rights reserved.
//

#import "ZLPSubDetailViewController.h"
#import "ZLPSubDeatilTableViewCellOne.h"
#import "ZLPSubDeatailTableViewCellTwo.h"
#import "ZLPSubDetailPics.h"
#import "ZLPSubDetailPostModel.h"
#import "ZLPSubDetailProductModel.h"
#import "ZLPSubDetailTagModel.h"
#import <UIImageView+WebCache.h>
#import "ZLPDetailViewController.h"
#import "ZLPSubDetailLikes_usersModel.h"
#import "ZLPRankCollectionViewCell.h"
#import "UMSocial.h"
#import "ZLPIsLoginHandle.h"
#import <AFNetworking.h>

@interface ZLPSubDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) UIView *headerView;
@property(nonatomic, retain) NSMutableArray *postArr;
@property(nonatomic, retain) NSMutableArray *picArr;
@property(nonatomic, retain) NSMutableArray *productArr;
@property(nonatomic, retain) NSMutableArray *tagArr;
@property(nonatomic, retain) UIView *footerView;
@property(nonatomic, retain) NSMutableArray *likeArr;
@property(nonatomic, retain) UILabel *likeLabel;
@property(nonatomic, retain) UICollectionView *collection;
@property(nonatomic, copy) NSString *shareUrl;

@end

@implementation ZLPSubDetailViewController

- (void)dealloc {
    [_shareUrl release];
    [_likeLabel release];
    [_collection release];
    [_likeArr release];
    [_footerView release];
    [_tagArr release];
    [_postArr release];
    [_picArr release];
    [_productArr release];
    [_headerView release];
    [_tableView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"好物详情";
    
    [self createTableView];
    
//    [self isWlan];
    
    [self createData];
    
//    [self createHeaderView];
    
    [self createFooterView];
    
    [self createCollectionView];
    
    [self createLikeLabel];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share.png"] style:UIBarButtonItemStylePlain target:self action:@selector(share:)];
}

- (void)isWlan {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 2 || status == 1) {
            
            [self createData];
            
        } else {
            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];

        }
        
    }];
}

- (void)createHeaderView {
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
    self.tableView.tableHeaderView = self.headerView;
    [_headerView release];
    
    UIImageView *avater = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
    [_headerView addSubview:avater];
    [avater release];
    
    
}

#pragma mark share的方法
- (void)share:(UIBarButtonItem *)button {
    
//    if ([ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin) {
    
        ZLPSubDetailPics *model = self.picArr[0];
        NSLog(@"%@", model.url);
        
//        [UMSocialSnsService presentSnsIconSheetView:self
//                                             appKey:@"563814b567e58efbc7003c2c"
//                                          shareText:[NSString stringWithFormat:@"我在#糖衣#发现了一个好东西. %@", self.shareUrl]
//                                         shareImage:[UIImage imageNamed:@"saber.jpeg"]
//                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, nil]
//                                           delegate:nil];
        
        UMSocialUrlResource *urlResource = [[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeImage url:model.url];
        [UMSocialData defaultData].urlResource = urlResource;
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"563814b567e58efbc7003c2c"
                                          shareText:[NSString stringWithFormat:@"我在#糖衣#发现了一个好东西. %@", self.shareUrl]
                                         shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,nil]
                                           delegate:nil];
        
        
      
        
//        UMSocialUrlResource *urlResource = [[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeImage url:model.url];
//        [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToSina]
//                                                           content:[NSString stringWithFormat:@"我在#糖衣#发现了一个好东西. %@", self.shareUrl]
// 
//                                                             image:model.url
//                                                          location:nil
//                                                       urlResource:urlResource presentedController:self completion:^(UMSocialResponseEntity *shareResponse){
//            if (shareResponse.responseCode == UMSResponseCodeSuccess) {
//            
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"分享成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                [alert show];
//                
//            }
//        }];
        
        
//    } else {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请先登陆" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
//    }
    
}

#pragma mark creataFooterView
- (void)createFooterView {
    self.footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 95)];
    self.tableView.tableFooterView = self.footerView;
    [_footerView release];
}

#pragma markcreateCollectonView
- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(50, 50);
    layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 35, WIDTH , 50) collectionViewLayout:layout];
    [self.footerView addSubview:self.collection];
    [_collection release];
    
    self.collection.backgroundColor = [UIColor whiteColor];
    self.collection.showsHorizontalScrollIndicator = NO;
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    [self.collection registerClass:[ZLPRankCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
    
    
    
}

- (void)createLikeLabel {
    self.likeLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 100, 20)];
    [self.footerView addSubview:self.likeLabel];
    [_likeArr release];
    self.likeLabel.textColor = [UIColor grayColor];
    self.likeLabel.font = [UIFont systemFontOfSize:13];
    self.likeLabel.text = @"喜欢列表";
}

#pragma mark createTableView
- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 14) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
}
#pragma mark createData
- (void)createData {
    NSString *strURL = @"http://open3.bantangapp.com/community/post/info";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = [NSString stringWithFormat:@"app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.1&screensize=640&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7", self.numID];
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            self.postArr = [NSMutableArray array];
            ZLPSubDetailPostModel *postModel = [[ZLPSubDetailPostModel alloc] init];
            [postModel setValuesForKeysWithDictionary:dic[@"data"][@"post"] ];
            [self.postArr addObject:postModel];
            [postModel release];
            
            self.shareUrl = dic[@"data"][@"post"][@"share_url"];
            
            self.picArr = [NSMutableArray array];
            self.picArr = [ZLPSubDetailPics baseModelByArr:dic[@"data"][@"post"][@"pics"]];
            
            self.tagArr = [NSMutableArray array];
            self.tagArr = [ZLPSubDetailTagModel baseModelByArr:dic[@"data"][@"post"][@"tags"]];
            
            self.productArr = [NSMutableArray array];
            self.productArr = [ZLPSubDetailProductModel baseModelByArr:dic[@"data"][@"post"][@"product"]];
            
            self.likeArr = [NSMutableArray array];
            self.likeArr = [ZLPSubDetailLikes_usersModel baseModelByArr:dic[@"data"][@"post"][@"dynamic"][@"likes_users"]];
            
            NSLog(@"like%ld", self.likeArr.count);
            
            if (self.likeArr.count == 0) {
                self.tableView.tableFooterView.hidden = YES;
                self.tableView.tableFooterView.frame = CGRectMake(0, 0, 0, 0);
                
            }
            
            [self.tableView reloadData];
            [self.collection reloadData];

        } else {
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];
        }
        
    }];
}

#pragma mark collection的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.likeArr.count <= 5 ) {
        return self.likeArr.count;
    } else {
        return self.collection.frame.size.width / 50 - 1;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPRankCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
 
    for (NSInteger i = 0; i < self.likeArr.count; i++) {
        [cell.rankImage sd_setImageWithURL:[NSURL URLWithString:[self.likeArr[indexPath.row] avatar]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    }
    
    return cell;
}

#pragma mark tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *reuse = @"reuse";
        ZLPSubDeatilTableViewCellOne *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[ZLPSubDeatilTableViewCellOne alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        
        ZLPSubDetailPics *picModel = [[ZLPSubDetailPics alloc] init];
        picModel = self.picArr[indexPath.row];
        
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:picModel.url] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        cell.descLabel.text = [self.postArr[indexPath.row] content];
        
        
        for (NSInteger i = 0; i < self.tagArr.count; i++) {
            if (i == 0) {
                cell.tagLabel.text = [self.tagArr[i] name];
            } else if (i == 1) {
                cell.tagLabel1.text = [self.tagArr[i] name];
            } else if (i == 2) {
                cell.tagLabel2.text = [self.tagArr[i] name];
            }
        }
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], NSFontAttributeName, nil];
        CGRect rect = [cell.descLabel.text boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        cell.tagLabel.frame = CGRectMake(30, WIDTH + rect.size.height + 15, 50, 20);
        [cell.tagLabel sizeToFit];
        cell.tagLabel.numberOfLines = 1;
        
        cell.tagLabel1.frame = CGRectMake(60 + cell.tagLabel.frame.size.width, WIDTH + rect.size.height + 15, 100, 20);
        [cell.tagLabel1 sizeToFit];
        cell.tagLabel1.numberOfLines = 1;
        
        cell.tagLabel2.frame = CGRectMake(90 + cell.tagLabel1.frame.size.width + cell.tagLabel.frame.size.width, WIDTH + rect.size.height + 15, 100, 20);
        [cell.tagLabel2 sizeToFit];
        cell.tagLabel2.numberOfLines = 1;
        
        cell.tagImageView.image = [UIImage imageNamed:@"tag.png"];
        
        return cell;
    } else {
        static NSString *reuse = @"icon";
        ZLPSubDeatailTableViewCellTwo *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[ZLPSubDeatailTableViewCellTwo alloc] init];
        }
        
        cell.iconImageView.image = [UIImage imageNamed:@"icon.png"];
        cell.iconLabel.text = @"相关链接";
        if (!self.productArr.count == 0) {
            
            
            
            [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:[self.productArr[indexPath.row] pic]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
            cell.titleLabel.text = [self.productArr[indexPath.row] title];
            cell.priceLabel.text = [NSString stringWithFormat:@"￥ %@", [self.productArr[indexPath.row] price]];
            if ([[self.productArr[indexPath.row] platform] isEqualToString:@"1"]) {
                cell.platformImageView.image = [UIImage imageNamed:@"taobao.png"];
                cell.platformLabel.text = @"来自淘宝";
            } else {
                cell.platformImageView.image = [UIImage imageNamed:@"tianmao.png"];
                cell.platformLabel.text = @"来自天猫";
            }
            
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        ZLPDetailViewController *detailVC = [[ZLPDetailViewController alloc] init];
        [self.navigationController pushViewController:detailVC animated:YES];
        
        ZLPSubDetailProductModel *model = [[ZLPSubDetailProductModel alloc] init];
        model = self.productArr[indexPath.row];
        
        detailVC.url = model.url;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.productArr.count == 0) {
        return 1;
    } else {
        return 2;
    }
    
}

//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    if (self.likeArr.count == 0) {
//        return 0;
//    } else {
//        return 95;
//    }
//}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
        CGRect rect = [[self.postArr[indexPath.row] content] boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        return WIDTH + rect.size.height + 40;
    } else {
        
        return 120;
        
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
